package com.woniuxy.controller;

import com.woniuxy.entity.MUser;
import com.woniuxy.service.UserService;
import com.woniuxy.util.JwtUtils;
import com.woniuxy.util.ResultVo;
import com.woniuxy.util.SendCommonPostMail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;
@Slf4j
@RestController
@Transactional
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("user/getCode")
    public ResultVo login(@RequestBody String email) throws IOException {
        String decode = URLDecoder.decode(email, "utf-8");
        String replace = decode.replace("=", "");
        System.out.println(replace);
        String code = SendCommonPostMail.SendMail(replace);
        redisTemplate.opsForValue().set(email,code);
        return ResultVo.success("发送成功");
    }

    @PostMapping("user/login")
    public ResultVo login(@RequestBody Map<String,Object> map){
        String userName = (String) map.remove("username");
        String passWord = (String) map.remove("password");
        if (!StringUtils.hasText(userName)) {
            throw new RuntimeException("用户名为空");
        }
        if (!StringUtils.hasText(passWord)) {
            throw new RuntimeException("密码为空");
        }
        MUser loginUser = userService.login(userName, passWord);

        String token = JwtUtils.createToken(Math.toIntExact(loginUser.getId()), 3600);
        log.info("生成token，放入用户ID"+loginUser.getId());
        return ResultVo.success("认证成功",token);
    }

    @PostMapping("user/loginByMailCode")
    public ResultVo loginByMailCode(@RequestBody Map<String,Object> map){
        String email = map.get("email").toString();
        String code = map.get("code").toString();
        if (!StringUtils.hasText(email)) {
            throw new RuntimeException("邮箱为空");
        }
        if (!StringUtils.hasText(code)) {
            throw new RuntimeException("验证码");
        }
        MUser loginUser = userService.loginByEmailCode(email, code);

        String token = JwtUtils.createToken(Math.toIntExact(loginUser.getId()), 3600);
        log.info("生成token，放入用户ID"+loginUser.getId());
        return ResultVo.success("认证成功",token);
    }

    @PostMapping("user/getLoginUser")
    public ResultVo getLoginUser(@RequestBody String token){
        MUser loginUser = userService.getLoginUser(token);
        return ResultVo.success("查询成功",loginUser);
    }
}
